package view;

import java.io.IOException;
import java.text.ParseException;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.LivroCaixaException;

import controller.Cashier;

/**
 * Servlet implementation class FileServlet
 */
public class FileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
      private Cashier cashier = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileServlet() {
        super();
        cashier = Cashier.getInstance();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String forward = "/Controller.jsp";
		String addOperationsByFileStatus = "";
		
		
		try {
			
			String fileContent = cashier.getFileContent(request.getParameter("file"));
			
			cashier.submitBankOperations(fileContent, (String) request.getSession().getAttribute("exibirConta"));
			cashier.generateReport(null, null, null, (String) request.getSession().getAttribute("exibirConta"));
			addOperationsByFileStatus = "Extrato inserido com sucesso...";
		} catch (LivroCaixaException e) {
			addOperationsByFileStatus = e.getMessage();
		} catch (ParseException e) {
			addOperationsByFileStatus = e.getMessage();
		}
				
		
		request.setAttribute("addOperationsByFileStatus", addOperationsByFileStatus);
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(forward);
		if (dispatcher != null) {
			dispatcher.forward(request, response);
		}
	}

}
